package cn.lml.lession.auth.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import cn.lml.lession.auth.service.impl.UserDetailsServiceImpl;


@Component
public class SecurityAuthenticationProvider implements AuthenticationProvider {
    
    private static final Logger logger = LoggerFactory.getLogger(SecurityAuthenticationProvider.class);
    
    @Autowired
	private UserDetailsServiceImpl userDetailsService;
    
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if(authentication == null){
            return null;
        }
        logger.debug("authentication:{}",authentication);
        String username = authentication.getName();
        logger.debug("authentication.getName();:{}",authentication.getName());
        String password = (String) authentication.getCredentials();
        logger.debug("password:{}",password);
        
        UserDetails user = userDetailsService.loadUserByUsername(username);
        logger.debug("user:{}",user);
        
        if(user == null){
            logger.debug("账户不存在user:{} ",user);
            throw new UsernameNotFoundException("账户不存在");
        }
        
        if(!user.getPassword().equals(password)){
            logger.debug("密码错误user:{} ",user);
            throw new UsernameNotFoundException("密码错误");
        }
        
        logger.debug("登录成功");
        return new UsernamePasswordAuthenticationToken(username,password, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
    
    
}
